<?php
/**
 * 海外仓-仓库信息
 * (model)
 */
namespace App\Models\OverSeasBa;

use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysPlat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Warehouse extends Model
{
    protected $table = 'os_b_warehouse';

    protected $guarded = [];

    protected $casts = [
        'warehouse_model'   => 'array',
        'warehouse_service' => 'array',
        'warehouse_range'   => 'array',
    ];

    /**
     * 仓库
     * @var string[]
     */
    const WAREHOUSE_BOX_FBA      = 1; //中转仓库（FBA）
    const WAREHOUSE_BOX_BUSINESS = 5; //中转仓库（经销商）
    const WAREHOUSE_REMOVALE     = 2; //移库仓库
    const WAREHOUSE_DROPSHIPPING = 3; //一件代发仓库
    const WAREHOUSE_RETURN       = 4; //退换货仓库
    public static $_warehouse = [
        self::WAREHOUSE_BOX_FBA      => '中转(FBA)',
        self::WAREHOUSE_BOX_BUSINESS => '中转(经销商)',
        self::WAREHOUSE_REMOVALE     => '移库',
        self::WAREHOUSE_DROPSHIPPING => '一件代发',
        self::WAREHOUSE_RETURN       => '退货',
    ];

    /**
     * 发货推荐(不包含中转)
     * @var string[]
     */
    public static $_warehouse_delivery = [
        self::WAREHOUSE_REMOVALE     => '移库',
        self::WAREHOUSE_DROPSHIPPING => '代发',
        self::WAREHOUSE_RETURN       => '退货',
    ];

    public static $_status = [
        0 => '停用',
        1 => '启用',
    ];

    public function area(){
        return $this->belongsTo(SysArea::class, 'area_id');
    }

    public function country(){
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public function warehouse_group(){
        return $this->belongsTo(WarehouseGroup::class,'group_id');
    }

    public function warehouse_models(){
        return $this->hasMany(WarehouseModel::class, 'warehouse_id', 'id');
    }

    public static function options($where = []){
        $query = $where ? self::query()->where(formatCondition($where)) : self::query();
        return $query->pluck('w_code','id');
    }

    public static function getAreaIdById($id){
        return self::query()->where('id',$id)->value('area_id');
    }

    public static function getIdsByCountryId($countryId){
        return self::query()->where('country_id',$countryId)->pluck('id');
    }

    public static function getIdsByAreaId($areaId){
        return self::query()->where('area_id',$areaId)->pluck('id');
    }

    public static function getIdByCode($code){
        return self::query()->where('w_code',$code)->value('id');
    }

    public static function getCodeById($id){
        return self::query()->where('id',$id)->value('w_code');
    }

    public static function getWarehouseById($id){
        return self::query()->find($id);
    }

    public static function getWarehouseByCode($Code){
        return self::query()->where('w_code',$Code)->first();
    }

    /**
     * 获取模型
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getModel($id){
        return self::query()->where('id',$id)->first();
    }

    /**
     * 验证仓库是否包含一件代发功能
     * @param $wareHouseId
     * @return array
     */
    public static function isWarehouseDropShipping($wareHouseId){
        $wareHouse = self::getWarehouseById($wareHouseId);
        $warehouseModel = $wareHouse->warehouse_model ?: [];
        $wCode = $wareHouse->w_code;
        if(in_array(self::WAREHOUSE_DROPSHIPPING, $warehouseModel)){
            return ['flag' => true,'code' => $wCode];
        }else{
            return ['flag' => false,'code' => $wCode];
        }
    }

    /**
     * 根据海外仓库id和skuid,获取该地区库存列表
     * @param $platId
     * @param $wareHouseIds
     * @param $pSkuId
     * @param int $maxNum
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getWarehouseAeraInventory($platId, $wareHouseIds, $pSkuId, $maxNum = 0){

        //一件代发库存(优先使用)
        $warehouseInventory = DropshippingInventoryFnsku::query()
            ->select('account_id', 'warehouse_id', DB::raw('sum(instant) as num'))
            ->whereIn('warehouse_id', $wareHouseIds)
            ->where('plat_id', $platId)
            ->where('psku_id', $pSkuId)
            ->groupBy(['account_id', 'warehouse_id'])
            ->orderBy('num', 'DESC')
            ->having('num', '>=', $maxNum)
            ->get();

        if (!$warehouseInventory && intval($platId) != 3) {
            //移库
            return RemovaleInventoryFNSku::query()
                ->select('account_id', 'warehouse_id', DB::raw('sum(instant) as num'))
                ->whereIn('warehouse_id', $wareHouseIds)
                ->where('psku_id', $pSkuId)
                ->groupBy(['account_id', 'warehouse_id'])
                ->orderBy('num', 'DESC')
                ->having('num', '>=', $maxNum)
                ->get();
        }

        return $warehouseInventory;
    }

}
